package com.example.NIO;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * 一个英文字节 = 1
 * 一个中文 = 3
 * 一个中文字符 = 2
 * 一个换行符 = 2
 */
public class NioFileChannel03 {
    public static void main(String[] args) throws IOException {
        File file = FileUtil.newFile("1.txt");
        FileUtil.initFile(file, "hello word/n你好/n我的天");
        FileInputStream fileInputStream = new FileInputStream(file);
        FileChannel fileChannel = fileInputStream.getChannel();

        File outfile = FileUtil.newFile("2.txt");
        FileOutputStream fileOutputStream = new FileOutputStream(outfile);
        FileChannel outFileChannel = fileOutputStream.getChannel();

        ByteBuffer byteBuffer = ByteBuffer.allocate(512);

        while (true) { // 循环读取
            /*
                public final Buffer clear() {
                    position = 0;
                    limit = capacity;
                    mark = -1;
                    return this;
                }
             */
            // 这里有一个重要的操作，不要忘记了
//            byteBuffer.clear(); // 清空 buffer
            int read = fileChannel.read(byteBuffer);
            if (read == -1) { // 表示读完
//                outFileChannel.write()
                break;
            }
            // 将 buffer 中的数据写入到 outFileChannel
            byteBuffer.flip();
            outFileChannel.write(byteBuffer);
            // 这里我翻转了两次，这样做的好处是不用操作 byteBuffer.clear()
            byteBuffer.flip();
        }
        fileInputStream.close();
        fileOutputStream.close();
        file.delete();
        outfile.delete();
    }

}
